const noticeApi = require('../../api/notice')

Page({
  data: {
    messageList: [],
    loading: false,
    hasMore: true,
    page: 1,
    size: 10,
    keyword: '',
    searchValue: '',
    refreshing: false,
    showDetailModal: false,
    selectedMessage: null
  },

  onLoad() {
    this.loadMessages()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  /**
   * 标记全部已读
   */
  async markAllAsRead() {
    try {
      wx.showLoading({
        title: '处理中...'
      })

      await noticeApi.markAllAsRead()

      wx.hideLoading()
      wx.showToast({
        title: '全部已标记为已读',
        icon: 'success'
      })

      // 刷新消息列表
      this.refreshData()

      // 通知首页刷新未读数量
      this.notifyHomePageRefresh()
    } catch (error) {
      wx.hideLoading()
      console.error('标记全部已读失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    }
  },

  /**
   * 通知首页刷新未读数量
   */
  notifyHomePageRefresh() {
    // 通过全局数据或事件通知首页刷新
    const pages = getCurrentPages()
    const homePage = pages.find(page => page.route === 'pages/index/index')
    if (homePage && homePage.loadUserData) {
      homePage.loadUserData()
    }
  },

  /**
   * 加载消息列表
   */
  async loadMessages(isRefresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        page: isRefresh ? 1 : this.data.page,
        size: this.data.size,
        title: this.data.keyword
      }

      const result = await noticeApi.getNoticeList(params)

      if (result && result.records) {
        // 预处理数据，格式化时间和内容预览
        const processedMessages = result.records.map(message => ({
          ...message,
          publishTimeFormatted: this.formatTime(message.publishTime),
          contentPreview: this.getContentPreview(message.content),
          statusName: this.getStatusName(message.status)
        }))

        const newList = isRefresh ? processedMessages : [...this.data.messageList, ...processedMessages]

        this.setData({
          messageList: newList,
          hasMore: result.records.length === this.data.size,
          page: isRefresh ? 2 : this.data.page + 1,
          loading: false,
          refreshing: false
        })
      } else {
        this.setData({
          loading: false,
          refreshing: false,
          hasMore: false
        })
      }
    } catch (error) {
      console.error('加载消息失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      this.setData({
        loading: false,
        refreshing: false
      })
    }
  },

  /**
   * 刷新数据
   */
  refreshData() {
    this.setData({
      messageList: [],
      page: 1,
      hasMore: true,
      refreshing: true
    })
    this.loadMessages(true)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMessages()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  /**
   * 执行搜索
   */
  onSearch() {
    this.setData({
      keyword: this.data.searchValue,
      messageList: [],
      page: 1,
      hasMore: true
    })
    this.loadMessages(true)
  },

  /**
   * 清空搜索
   */
  onClearSearch() {
    this.setData({
      searchValue: '',
      keyword: '',
      messageList: [],
      page: 1,
      hasMore: true
    })
    this.loadMessages(true)
  },

  /**
   * 点击消息项
   */
  async onMessageTap(e) {
    const { message } = e.currentTarget.dataset

    try {
      // 标记消息为已读
      await noticeApi.markAsRead(message.id)

      // 获取消息详情
      const result = await noticeApi.getNoticeDetail(message.id)

      if (result) {
        const detailMessage = {
          ...result,
          publishTimeFormatted: this.formatTime(result.publishTime)
        }

        this.setData({
          selectedMessage: detailMessage,
          showDetailModal: true
        })

        // 更新消息列表中的已读状态
        this.updateMessageReadStatus(message.id)

        // 通知首页刷新未读数量
        this.notifyHomePageRefresh()
      } else {
        wx.showToast({
          title: '获取消息详情失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取消息详情失败:', error)
      wx.showToast({
        title: error.message || '获取详情失败',
        icon: 'none'
      })
    }
  },

  /**
   * 隐藏详情弹窗
   */
  hideDetailModal() {
    this.setData({
      showDetailModal: false,
      selectedMessage: null
    })
  },

  /**
   * 更新消息已读状态
   */
  updateMessageReadStatus(messageId) {
    const messageList = this.data.messageList.map(message => {
      if (message.id === messageId) {
        return {
          ...message,
          isRead: true
        }
      }
      return message
    })

    this.setData({
      messageList
    })
  },

  /**
   * 标记所有消息为已读
   */
  async markAllAsRead() {
    try {
      await noticeApi.markAllAsRead()

      // 更新所有消息的已读状态
      const messageList = this.data.messageList.map(message => ({
        ...message,
        isRead: true
      }))

      this.setData({
        messageList
      })

      wx.showToast({
        title: '已标记全部已读',
        icon: 'success'
      })
    } catch (error) {
      console.error('标记全部已读失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timeStr) {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  /**
   * 获取内容预览
   */
  getContentPreview(content) {
    if (!content) return ''
    
    // 移除HTML标签，获取纯文本
    const textContent = content.replace(/<[^>]*>/g, '')
    
    // 限制预览长度
    return textContent.length > 50 ? textContent.substring(0, 50) + '...' : textContent
  },

  /**
   * 获取状态名称
   */
  getStatusName(status) {
    switch (status) {
      case 0:
        return '草稿'
      case 1:
        return '已发布'
      case 2:
        return '已下线'
      default:
        return '未知'
    }
  }
})
